package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.dto.CustomerInfoDTO;
import com.qianying.entity.CustomerInfo;
import com.qianying.mapper.CustomerInfoMapper;
import com.qianying.service.ChinaAreaService;
import com.qianying.service.CustomerInfoService;
import com.qianying.vo.CustomerInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

@Service
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private CustomerInfoMapper customerMapper;
    @Autowired
    private ChinaAreaService chinaAreaService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<?> addCustomer(CustomerInfoDTO dto) {
        CustomerInfo entity = new CustomerInfo();
        BeanUtils.copyProperties(dto, entity);
        entity.setId(null);
        // 保存客户信息
        boolean success = this.save(entity);
        if (success) {
            return CommonResult.success(entity, "保存成功！");
        } else {
            return CommonResult.failed("保存失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<?> updateCustomer(CustomerInfoDTO dto) {
        CustomerInfo entity = this.getById(dto.getId());
        if (entity == null) {
            throw new IllegalArgumentException("客户ID不存在: " + dto.getId());
        }

        // 复制DTO中的非空属性到实体
        BeanUtils.copyProperties(dto, entity, getNullPropertyNames(dto));

        boolean success = this.updateById(entity);
        if (success) {
            return CommonResult.success(entity, "更新成功！");
        } else {
            return CommonResult.failed("更新！");
        }
    }

    @Override
    public CommonResult<?> deleteCustomerById(Long id) {
        boolean success = this.removeById(id);
        if (success) {
            return CommonResult.success("删除用户信息成功！！");
        } else {
            return CommonResult.failed("删除用户信息成功失败！");
        }
    }

    @Override
    public CommonResult<?> getAllCustomers(Long province, Long city, Long district) {
        QueryWrapper<CustomerInfo> wrapper = new QueryWrapper<>();
        List<CustomerInfo> list;
        if (province != null) {
            wrapper.eq("province", province);
        }
        if (city != null) {
            wrapper.eq("city", city);
        }
        if (district != null) {
            wrapper.eq("district", district);
        }
        list = customerMapper.selectList(wrapper);
        if (list.isEmpty()) {
            return CommonResult.failed("没有初查询到符合条件的信息！");
        }
        Map<Long, String> map = chinaAreaService.IdToNameMap();
        List<CustomerInfoVo> dtoInforList = new ArrayList<>();
        for (CustomerInfo customerInfo : list) {
            CustomerInfoVo customerInfoVo = new CustomerInfoVo();
            BeanUtils.copyProperties(customerInfo, customerInfoVo);
            if (map.containsKey(customerInfo.getProvince())) {
                customerInfoVo.setProvinceName(map.get(customerInfo.getProvince()));
            }
            if (map.containsKey(customerInfo.getCity())) {
                customerInfoVo.setCityName(map.get(customerInfo.getCity()));
            }
            if (map.containsKey(customerInfo.getDistrict())) {
                customerInfoVo.setDistrictName(map.get(customerInfo.getDistrict()));
            }
            dtoInforList.add(customerInfoVo);
        }
        return CommonResult.success(dtoInforList, "获取客户信息成功！");
    }


    /**
     * 获取对象中为空的属性名数组
     */
    private String[] getNullPropertyNames(Object source) {
        org.springframework.beans.BeanWrapper src = new org.springframework.beans.BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        java.util.Set<String> emptyNames = new java.util.HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 获取所有客户ID与名称的映射Map
     * 包含系统中所有客户记录，键为客户ID，值为客户名称
     *
     * @return 全量客户ID-名称映射Map
     */
    @Override
    public Map<Long, String> getAllCustomerIdNameMap() {
        // 查询所有客户记录
        List<CustomerInfo> customers = customerMapper.selectList(null);

        // 处理空列表情况
        if (customers == null || customers.isEmpty()) {
            return new HashMap<>(0);
        }

        // 转换为ID-名称映射Map
        return customers.stream()
                .collect(Collectors.toMap(
                        CustomerInfo::getId,        // 键：客户ID
                        CustomerInfo::getCustomerName,  // 值：客户名称
                        (existing, replacement) -> existing  // 处理ID重复（保留第一条）
                ));
    }
}